package com.rc.saas.tenant.service.elec;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.utils.NumberUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.elec.ElecPileHostMapper;
import com.rc.saas.tenant.mapper.elec.ElecPileMapper;
import com.rc.saas.tenant.mapper.elec.ElecStationMapper;
import com.rc.saas.tenant.mapper.order.OrderInfoMapper;
import com.rc.saas.tenant.model.elec.*;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantManufacturer;
import com.rc.saas.tenant.model.tenant.TenantManufacturerExample;
import com.rc.saas.tenant.search.StatisticsSearch;
import com.rc.saas.tenant.search.elec.ElecPileFailureSearch;
import com.rc.saas.tenant.search.elec.ElecPileSearch;
import com.rc.saas.tenant.search.elec.PileOfflineSearch;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.tenant.TenantManufacturerService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.vo.elec.*;
import com.rc.saas.tenant.vo.tenant.TenantUserRoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by sven on 2018-04-17
 */
@Service
public class ElecPileServiceImpl implements ElecPileService {

    @Autowired
    private ElecPileMapper elecPileMapper;

    @Autowired
    @Lazy
    private ElecGunService elecGunService;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private ElecStationMapper elecStationMapper;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantManufacturerService tenantManufacturerService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ElecPileHostMapper elecPileHostMapper;

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Override
    public ElecPileMapper getMapper() {
        return elecPileMapper;
    }

    @Override
    public long countLoginPile(String tenantCode) {
        long loginPileCount = elecStationMapper.countLoginPile(tenantCode);
        return loginPileCount;
    }

    @Override
    public long countPile(String tenantCode, String pileType) {
        long pileCount = elecPileMapper.countPile(tenantCode, pileType);
        return pileCount;
    }

    @Override
    public PageInfo<ElecPileResultVo> listPagePile(ElecPileSearch elecPileSearchVo) {
        TenantUserRoleVo userRoleVo = tenantRoleService.getLonginRole(elecPileSearchVo.getLoginName());
        if (userRoleVo!=null){
            elecPileSearchVo.setRoleType(userRoleVo.getRoleType());
            elecPileSearchVo.setDataAuth(userRoleVo.getDataAuth());
            switch (userRoleVo.getRoleType()){
                case "1"://自定义用户
                    elecPileSearchVo.setOperatorIds(
                            StringUtils.isNotBlank(userRoleVo.getOperatorIds())?
                                    Arrays.asList(userRoleVo.getOperatorIds().split(","))
                                    :new ArrayList<String>());
                    elecPileSearchVo.setEnterpriseIds(
                            StringUtils.isNotBlank(userRoleVo.getEnterpriseIds())?
                                    Arrays.asList(userRoleVo.getEnterpriseIds().split(","))
                                    :new ArrayList<String>());
                    break;
                case "2"://加盟商用户
                    elecPileSearchVo.setOperatorIds(StringUtils.isNotBlank(userRoleVo.getOperatorIds())?
                            Arrays.asList(userRoleVo.getOperatorIds().split(","))
                            :new ArrayList<String>());
                    break;
                case "3"://企业用户
                    elecPileSearchVo.setEnterpriseIds(StringUtils.isNotBlank(userRoleVo.getEnterpriseIds())?
                            Arrays.asList(userRoleVo.getEnterpriseIds().split(","))
                            :new ArrayList<String>());
                    break;
            }
        }
        PageHelper.startPage(elecPileSearchVo.getOffset(), elecPileSearchVo.getLimit());
        List<ElecPileResultVo> elecPileList = elecPileMapper.listByCondition(elecPileSearchVo);
        return new PageInfo<ElecPileResultVo>(elecPileList);

    }

    @Override
    public List<ElecPile> listPileByStationId(Long stationId) {
        ElecPileExample example = new ElecPileExample();
        example.createCriteria().andElecStationIdEqualTo(stationId);
        List<ElecPile> elecPileList = elecPileMapper.selectByExample(example);
        return elecPileList;
    }

    @Override
    public void deletePileAndGun(Long elecPileId) {
        List<ElecGun> elecGuns = elecGunService.listGunByPileId(elecPileId);
        for (ElecGun elecGun : elecGuns) {
            elecGunService.deleteByPrimaryKey(elecGun.getElecGunId());
        }
        elecPileMapper.deleteByPrimaryKey(elecPileId);
    }

    @Override
    public void changeStatus(Long elecPileId) {
        ElecPile elecPile = elecPileMapper.selectByPrimaryKey(elecPileId);
        List<ElecGun> elecGuns = elecGunService.listGunByPileId(elecPileId);
        if ("1".equals(elecPile.getOperateStatus())) {
            changePileAndGun(elecPile, elecGuns, "2");
        } else {
            changePileAndGun(elecPile, elecGuns, "1");
        }
    }

    @Override
    public BigDecimal sumTotalPowerByEpg(String tenantCode) {
        BigDecimal totalPowerByEpg = elecStationMapper.sumTotalPowerByEpg(tenantCode);
        return totalPowerByEpg;
    }

    @Override
    public ElecPile selectLastPileNo(String tenantCode, String pileNo) {
        ElecPileExample elecPileExample = new ElecPileExample();
        elecPileExample.createCriteria().andPileNoEqualTo(pileNo);

        List<ElecPile> elecPiles = elecPileMapper.selectByExample(elecPileExample);
        if (CollectionUtils.isEmpty(elecPiles)) {
            return null;
        }
        return elecPiles.get(0);
    }

    /**
     * pileNo 桩编号, 12位字符 4位运营商前缀+2位省ID+6位流水号
     *
     * @param elecPile
     * @param tenantCode
     * @param loginName
     */
    @Override
    public synchronized TResponse saveOrUpdateElecPile(ElecPile elecPile, String tenantCode, String loginName) {

        ElecStation elecStation = elecStationMapper.selectByPrimaryKey(elecPile.getElecStationId());
        Date date = new Date();
        elecPile.setTenantCode(tenantCode);
        elecPile.setLastUpdatedBy(loginName);
        elecPile.setLastUpdatedTime(date);
        if (elecStation!=null){
            elecPile.setOperatorId(elecStation.getOperatorId());
        }
        //更新
        if (elecPile.getElecPileId() != null) {
            ElecPile oldPile = elecPileMapper.selectByPrimaryKey(elecPile.getElecPileId());
            if (oldPile == null) {
                return TResponse.FAIL("更新失败,请联系研发");
            }
            elecPileMapper.updateByPrimaryKeySelective(elecPile);

            elecGunService.updateGunOperators(elecPile.getElecPileId(),elecPile.getOperatorId(),elecPile.getElecStationId());
        } else {
            String newPileNo = null;
            ElecPile elecPileInfo = elecPileMapper.selectLastPileNo(tenantCode, elecStation.getElecStationId());
            if (elecPileInfo == null) {
                //生成第一个桩编号
                newPileNo = elecStation.getStationNo() + "001";
            } else {
                //自增桩编号
                newPileNo = StringUtil.newNo(elecPileInfo.getPileNo(), 3);
            }
            elecPile.setPileNo(newPileNo);

            //得到ASCII码地址
            elecPile.setPileRtua(NumberUtil.bin2HexStr(newPileNo.getBytes()));
            //+1
            String newPileNo1 = StringUtil.newNo(newPileNo, 3);
            //新增从属桩编号
            elecPile.setPileNoSlave(newPileNo1);

            ElecPileExample example = new ElecPileExample();
            example.createCriteria().andPileNoEqualTo(newPileNo);
            List<ElecPile> elecPiles = elecPileMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(elecPiles)) {
                return TResponse.FAIL("生成桩编号异常,请联系研发");
            }
            elecPile.setCreatedBy(loginName);
            elecPile.setCreatedTime(date);
            elecPileMapper.insertSelectiveReturnId(elecPile);
        }
        return TResponse.SUCCESS();
    }

    @Override
    public ElecPileStatusCountVo selectCountByPileStatus(String tenantCode, Long eleStationId) {
        ElecPileStatusCountVo elecPileStatusCountVo = elecPileMapper.countByPileStatus(tenantCode, eleStationId, null);
        return elecPileStatusCountVo;
    }

    @Override
    public ElecPileStatusCountVo selectCountByPileStatus(String tenantCode, Long eleStationId, String bizType) {
        ElecPileStatusCountVo elecPileStatusCountVo = elecPileMapper.countByPileStatus(tenantCode, eleStationId, bizType);
        return elecPileStatusCountVo;
    }

    @Override
    public ElecPileStatusCountVo selectCountByPileStatusOperator(String tenantOperatorCode, Long eleStationId) {
        List<Long> eleStationIds = elecStationMapper.listStationIdByOperator(tenantOperatorCode);
        ElecPileStatusCountVo elecPileStatusCountVo = elecPileMapper.countByPileStatusOperator(eleStationIds, eleStationId);
        return elecPileStatusCountVo;
        //return new ElecPileStatusCountVo();
    }

    @Override
    public PageInfo<ElecPile> searchPileFailure(ElecPileFailureSearch elecPileFailureSearch) {
        return null;
    }

    private void changePileAndGun(ElecPile elecPile, List<ElecGun> elecGuns, String s) {
        elecPile.setOperateStatus(s);
        elecPileMapper.updateByPrimaryKeySelective(elecPile);
        for (ElecGun elecGun : elecGuns) {
            elecGun.setOperateStatus(s);
            elecGunService.updateByPrimaryKeySelective(elecGun);
        }
    }


    @Override
    public ElecPile selectByOperatorIdAndPileNo(String tenantCode, String hlhtOperatorId, String hlhtPileNo) {
        ElecPileExample example = new ElecPileExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andHlhtOperatorIdEqualTo(hlhtOperatorId).andHlhtPileNoEqualTo(hlhtPileNo);
        List<ElecPile> list = elecPileMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    //    /**
//     * todo 得到桩编号
//     *
//     * @param prefix
//     * @param provinceId
//     * @param oldPileNo
//     * @return
//     */
    //protected synchronized String addPileNo(String prefix, String provinceId, String oldPileNo) {
    //    provinceId = provinceId.substring(0, provinceId.length() - 4);
    //    if (oldPileNo == null) {
    //        return prefix + provinceId + "000011";
    //    }
    //
    //    String lastNo = oldPileNo.substring(6, 11);
    //    int no = Integer.valueOf(lastNo);
    //    no += 1;
    //    if (no > 99999) {
    //    }
    //    String format = String.format("%05d", no);
    //    return prefix + provinceId + format + "1";
    //}
    @Override
    public void updateBatchElecPileOperateStatusByElecStationIdList(List<Long> elecStationIdList, String operateStatus, Integer status) {
        elecPileMapper.updateBatchElecPileOperateStatusByElecStationIdList(elecStationIdList, operateStatus, status);
    }

    @Override
    public PageInfo<ElecPile> listPageElecPile(ElecPileSearch elecPileSearch) {
        PageHelper.startPage(elecPileSearch.getOffset(), elecPileSearch.getLimit());
        List<ElecPile> elecPileList = elecPileMapper.listPageElecPile(elecPileSearch);
        return new PageInfo<>(elecPileList);
    }

    @Override
    public List<ElecPile> listElecPileByStationIdList(List<Long> elecStationIdList) {
        return elecPileMapper.listElecPileByStationIdList(elecStationIdList);
    }

    @Override
    public List<ElecPile> listElecPileByElecPileIdList(List<Long> elecPileIdList) {
        return elecPileMapper.listElecPileByElecPileIdList(elecPileIdList);
    }

    @Override
    public PageInfo<PileOfflineVo> listPagePileOffline(PileOfflineSearch pileOfflineSearch) {
        PageHelper.startPage(pileOfflineSearch.getOffset(), pileOfflineSearch.getLimit());
        List<PileOfflineVo> elecPileList = elecPileMapper.listPagePileOffline(pileOfflineSearch);
        return new PageInfo<>(elecPileList);
    }

    @Override
    public PileOfflineVo selectPileOfflineInfo(Long elecPileId, Date beginTime, Date endTime) {
        return elecPileMapper.selectPileOfflineInfo(elecPileId, beginTime, endTime);
    }

    @Override
    public PileOffineStatisticsVo selectPileOffineStatistics(String tenantCode) {
        PileOffineStatisticsVo pileOffineStatisticsVo = elecPileMapper.selectPileOffineStatistics(tenantCode);
        //将结果转化成百分比
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(2);
        float pileOnlineCount = (float) (pileOffineStatisticsVo.getTotalPileCount() - pileOffineStatisticsVo.getPileOffineCount()) / pileOffineStatisticsVo.getTotalPileCount();
        pileOffineStatisticsVo.setPileOnlineRate(percent.format(pileOnlineCount));
        return pileOffineStatisticsVo;
    }

    @Override
    public List<PileOfflineVo> listPileOffline(PileOfflineSearch pileOfflineSearch) {
        return elecPileMapper.listPagePileOffline(pileOfflineSearch);
    }

    @Override
    public List<ElecPile> selectListPiles(String tenantCode) {
        ElecPileExample example = new ElecPileExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode);
        List<ElecPile> elecPiles = elecPileMapper.selectByExample(example);
        return elecPiles;
    }

    @Override
    public StationAllDataVo countPileInConsole(StatisticsSearch search) {
        return elecPileMapper.countPileInConsole(search);
    }

    @Override
    public List<ElecPile> listByElecStationId(Long elecStationId) {
        ElecPileExample example = new ElecPileExample();
        example.createCriteria().andElecStationIdEqualTo(elecStationId);
        List<ElecPile> elecPiles = elecPileMapper.selectByExample(example);
        return elecPiles;
    }

    @Override
    public void updateOperatorBySId(ElecStation elecStation) {
        elecPileMapper.updateOperatorBySId(elecStation);
    }

    /**
     * 跳转枪列表
     *
     * @return
     */
    @RequestMapping(value = "/elecGunSub/{elecStationId}", method = RequestMethod.GET)
    public String elecGunSub(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecGun";
    }
}
